package com.lihegang.example.component;

import com.lihegang.example.util.configuration.RoncooJavaMailSenderImpl;
import freemarker.template.MalformedTemplateNameException;
import freemarker.template.TemplateException;
import freemarker.template.TemplateNotFoundException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import javax.mail.MessagingException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.ParseException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

/**
 *
 * @author wujing
 */
@Component
public class RoncooJavaMailComponent {
   private static final String template = "mail/mailTemplate.ftl";
 
   @Autowired
   private FreeMarkerConfigurer freeMarkerConfigurer;
   @Autowired
   private RoncooJavaMailSenderImpl javaMailSender;
 
   public void sendMail(String email) {
      Map<String, Object> map = new HashMap<String, Object>();
      map.put("email", email);
      map.put("content","我是邯郸开发区西鸭池人士，我中了彩票了！");
      try {
        String text = getTextByTemplate(template, map);
         send(email, text);
      } catch (MessagingException e) {
         e.printStackTrace();
      } catch (UnsupportedEncodingException e) {
         e.printStackTrace();
      } catch (MalformedTemplateNameException e) {
         e.printStackTrace();
      } catch (TemplateException e) {
         e.printStackTrace();
      } catch (TemplateNotFoundException e) {
         e.printStackTrace();
      } catch (IOException e) {
         e.printStackTrace();
      }
   }
 
   private String getTextByTemplate(String template, Map<String, Object> model) throws TemplateNotFoundException, MalformedTemplateNameException, ParseException, IOException, TemplateException {
      return FreeMarkerTemplateUtils.processTemplateIntoString(freeMarkerConfigurer.getConfiguration().getTemplate(template), model);
   }
 
   private String send(String email, String text) throws MessagingException, UnsupportedEncodingException {
      MimeMessage message = javaMailSender.createMimeMessage();
      MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8");
      InternetAddress from = new InternetAddress();
      from.setAddress(javaMailSender.getUsername());
      from.setPersonal("我爱董军娥", "UTF-8");
      helper.setFrom(from);
      helper.setTo(email);
      helper.setSubject("毕业论文设计");
      helper.setText(text, true);
      javaMailSender.send(message);
      return text;
   }
 
}